package com.yf.ability.upload.providers.oss.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.imm.model.v20170906.CreateOfficeConversionTaskRequest;
import com.aliyuncs.imm.model.v20170906.CreateOfficeConversionTaskResponse;
import com.aliyuncs.imm.model.v20170906.GetOfficeConversionTaskRequest;
import com.aliyuncs.mts.model.v20140618.SubmitJobsRequest;
import com.aliyuncs.mts.model.v20140618.SubmitJobsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.yf.ability.config.dto.CfgPropDTO;
import com.yf.ability.config.enums.ConfigType;
import com.yf.ability.config.enums.ProviderType;
import com.yf.ability.config.service.CfgPropService;
import com.yf.ability.upload.providers.local.utils.OssUtils;
import com.yf.ability.upload.providers.oss.dto.OssTokenDTO;
import com.yf.base.api.api.ApiError;
import com.yf.base.api.exception.ServiceException;
import com.yf.ability.upload.providers.oss.service.OssService;
import com.yf.ability.upload.providers.oss.config.OssConfig;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;

/**
 * OSS业务类
 *
 * @author bool
 */
@Log4j2
@Service
public class OssServiceImpl implements OssService {


    private static final String CTV_TEMPLATE = "S00000001-200000";


    @Autowired
    private CfgPropService cfgPropService;


    @Override
    public String convertDoc(String input) throws ClientException {

        // 查找配置
        OssConfig conf = this.getConfig();

        // bucket
        String bucket = conf.getBucket();

        // 转换区位
        String endPoint = conf.getEndpoint().replace("oss-", "");

        // 替换访问域名则是正确的bucket路径
        String fileName = input.replace(conf.getUrl(), "");

        // 文档转换项目
        String project = conf.getProject();


        // 初始化客户端
        IAcsClient cvtClient = new DefaultAcsClient(DefaultProfile.getProfile(endPoint, conf.getAccessKeyId(),
                conf.getAccessKeySecret()));

        // 创建文档转换异步请求任务。
        CreateOfficeConversionTaskRequest req = new CreateOfficeConversionTaskRequest();

        req.setProject(project);
        //设置待转换文件的OSS URI。
        req.setSrcUri("oss://" + bucket + "/" + fileName);
        //设置文件输出格式为vector。
        req.setTgtType("pdf");
        //设置转换后文件的输出路径。
        req.setTgtUri("oss://" + bucket + "/" + fileName);

        String taskId = null;

        System.out.println("+++++");

        try {
            CreateOfficeConversionTaskResponse res = cvtClient.getAcsResponse(req);
            taskId = res.getTaskId();
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }


        //获取文档转换任务结果，最多轮询30次。
        //每次轮询的时间间隔为1秒。
        GetOfficeConversionTaskRequest getOfficeConversionTaskRequest = new GetOfficeConversionTaskRequest();
        getOfficeConversionTaskRequest.setProject(project);
        getOfficeConversionTaskRequest.setTaskId(taskId);

//        int maxCount = 30;
//        int count = 0;
//        try {
//            while (true) {
//
//                log.error("++++++++++轮询结果:" + count);
//
//                //轮询的时间间隔，单位为毫秒。
//                Thread.sleep(2000);
//                GetOfficeConversionTaskResponse getOfficeConversionTaskResponse =
//                        cvtClient.getAcsResponse(getOfficeConversionTaskRequest);
//
//
//                log.error("++++++++++执行结果：{}", JSON.toJSONString(getOfficeConversionTaskResponse));
//
//                if (!getOfficeConversionTaskResponse.getStatus().equals("Running")) {
//
//                    log.error("++++++++++执行完成++++");
//
//                    //输出文档转换任务执行结果。
//                    System.out.println(getOfficeConversionTaskResponse.getTaskId());
//                    System.out.println(getOfficeConversionTaskResponse.getFailDetail().getCode());
//                    System.out.println("Done");
//                    break;
//                }
//
//                count = count + 1;
//                if (count >= maxCount) {
//                    System.out.println("OfficeConversion Timeout for 30 seconds");
//                    log.error("++++++++++轮询30次未果:");
//                    break;
//                }
//                System.out.println("Task is still running.");
//            }
//        } catch (InterruptedException e) {
//
//
//            log.error("++++++++++转换错误:" + e.getMessage());
//
//            e.printStackTrace();
//        }

        return conf.getUrl() + fileName + "/1.pdf";

    }

    @Override
    public String convertVideo(String url) {

        // 查找配置
        OssConfig conf = this.getConfig();

        // bucket
        String ossBucket = conf.getBucket();

        // 转换区位
        String ossLocation = conf.getEndpoint();

        // 替换访问域名则是正确的bucket路径
        String ossInputObject = url.replace(conf.getUrl(), "");

        log.info("+++++输入资源：{}", ossInputObject);

        // 输出文件名
        String ossOutputObject = ossInputObject + ".mp4";


        // 创建DefaultAcsClient实例并初始化
        DefaultProfile profile = DefaultProfile.getProfile(
                ossLocation.replace("oss-", ""),      // 地域ID
                conf.getAccessKeyId(),      // RAM账号的AccessKey ID
                conf.getAccessKeySecret()); // RAM账号Access Key Secret
        IAcsClient client = new DefaultAcsClient(profile);
        // 创建API请求并设置参数
        SubmitJobsRequest request = new SubmitJobsRequest();
        // Input
        JSONObject input = new JSONObject();
        input.put("Location", ossLocation);
        input.put("Bucket", ossBucket);
        try {
            input.put("Object", URLEncoder.encode(ossInputObject, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("input URL encode failed");
        }
        request.setInput(input.toJSONString());
        // Output
        String outputOSSObject;
        try {
            outputOSSObject = URLEncoder.encode(ossOutputObject, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("output URL encode failed");
        }
        JSONObject output = new JSONObject();
        output.put("OutputObject", outputOSSObject);
        // Ouput->Container
        JSONObject container = new JSONObject();
        container.put("Format", "mp4");
        output.put("Container", container.toJSONString());
        // Ouput->Video
        JSONObject video = new JSONObject();
        video.put("Codec", "H.264");
        video.put("Bitrate", "1500");
        video.put("Width", "1280");
        video.put("Fps", "25");
        output.put("Video", video.toJSONString());
        // Ouput->Audio
        JSONObject audio = new JSONObject();
        audio.put("Codec", "AAC");
        audio.put("Bitrate", "128");
        audio.put("Channels", "2");
        audio.put("Samplerate", "44100");
        output.put("Audio", audio.toJSONString());
        // Ouput->TemplateId
        output.put("TemplateId", CTV_TEMPLATE);
        JSONArray outputs = new JSONArray();
        outputs.add(output);
        request.setOutputs(outputs.toJSONString());
        request.setOutputBucket(ossBucket);
        request.setOutputLocation(ossLocation);
        // PipelineId
        request.setPipelineId(conf.getPipeline());
        // 发起请求并处理应答或异常
        SubmitJobsResponse response;
        try {
            response = client.getAcsResponse(request);
            log.info("++++++++++MPS转换请求ID:{}", response.getRequestId());
            if (response.getJobResultList().get(0).getSuccess()) {
                return conf.getUrl() + ossOutputObject;
            } else {
                throw new ServiceException("MPS转换失败：" + response.getJobResultList().get(0).getCode() + ":" + response.getJobResultList().get(0).getMessage());
            }
        } catch (Exception e) {
            throw new ServiceException("MPS转换出现问题");
        }
    }

    @Override
    public String upload(String localFile) {

        // 获取配置文件
        OssConfig conf = this.getConfig();

        // 安排上传后的文件名
        String ossPath = OssUtils.processPath(localFile);

        // 上传文件
        try {
            this.putObject(conf, ossPath, new FileInputStream(localFile));
        } catch (IOException e) {
            e.printStackTrace();
            //文件异常
            throw new ServiceException(ApiError.ERROR_10010001);
        }

        //返回结果
        return conf.getUrl() + ossPath;
    }

    @Override
    public OssTokenDTO token() {

        // 获得上传配置
        OssConfig conf = this.getConfig();

        // 请填写您的AccessKeyId。
        String accessId = conf.getAccessKeyId();
        // 请填写您的AccessKeySecret。
        String accessKey = conf.getAccessKeySecret();
        // 请填写您的 endpoint。
        String endpoint = conf.getEndpoint() + ".aliyuncs.com";
        // 请填写您的 bucketname 。
        String bucket = conf.getBucket();
        // host的格式为 bucketname.endpoint
        String host = "https://" + bucket + "." + endpoint;
        // 用户上传文件时指定的前缀。
        String dir = "";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        try {

            // 授权3个小时有效
            Calendar cl = Calendar.getInstance();
            cl.setTimeInMillis(System.currentTimeMillis());
            cl.add(Calendar.MINUTE, 180);



            PolicyConditions policyConds = new PolicyConditions();

            // 最大上传5G
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 5242888000L);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(cl.getTime(), policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);


            // 返回给前端使用
            OssTokenDTO respDTO = new OssTokenDTO();
            respDTO.setAccessId(accessId);
            respDTO.setPolicy(encodedPolicy);
            respDTO.setSignature(postSignature);
            respDTO.setDir(dir);
            respDTO.setHost(host);
            respDTO.setExpire(cl.getTimeInMillis() / 1000);
            respDTO.setUrl(conf.getUrl());

            return respDTO;
        } catch (Exception e) {
            log.error(e);
            throw new ServiceException("OSS上传令牌获取失败！");
        } finally {
            ossClient.shutdown();
        }
    }

    /**
     * 获取配置文件
     * @return
     */
    private OssConfig getConfig(){
        CfgPropDTO dto = cfgPropService.detail(ConfigType.UPLOAD, ProviderType.ALIYUN);
        OssConfig cfg = JSON.parseObject(dto.getData(), OssConfig.class);
        return cfg;
    }


    /**
     * 获得上传实例
     * @return
     */
    private OSSClient getClient(OssConfig conf){

        if(conf == null
                || StringUtils.isBlank(conf.getAccessKeyId())
                || StringUtils.isBlank(conf.getAccessKeySecret())
                || StringUtils.isBlank(conf.getEndpoint())){
            throw new ServiceException("OSS配置文件错误！");
        }

        // 鉴权
        CredentialsProvider credentials = new DefaultCredentialProvider(conf.getAccessKeyId(), conf.getAccessKeySecret());

        // 初始化上传节点，数据库未配置节点信息
        return new OSSClient(conf.getEndpoint() + ".aliyuncs.com", credentials, null);
    }


    /**
     * 获得上传实例
     * @return
     */
    private void putObject(OssConfig conf, String filePath, InputStream is){

        // 配置文件属性
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setCacheControl("max-age=31536000");
        // 上传文件
        this.getClient(conf).putObject(conf.getBucket(), filePath, is, metadata);
    }
}
